package com.example.websocketserver.util;

import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
@Component
public class InstanceUtil {
    //微服务注册成功标志.0:成功,其他失败
    public static int REGIST_STATUS = -1;

    //心跳失败次数
    public static int FAIL_TIME = 0;

    private static String instanceId = "standalone:20000";
    private static String hostName = "lenovo-PC104";
    private static String app = "standalone";
    private static String ipAddr = "127.0.0.1";
    private static String status = "UP";
    private static String port = "15000";
    private static String homePageUrl = "http://lenovo-PC104:15000";
    private static String statusPageUrl = "http://lenovo-PC104:15000/info";
    private static String healthCheckUrl = "http://lenovo-PC104:15000/health";
    private static String vipAddress = "standalone";
    private static String secureVipAddress = "standalone";


    public static String createXml() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            //根节点
            Element instance = document.createElement("instance");


            Element instanceIdElement = document.createElement("instanceId");
            instanceIdElement.setTextContent(instanceId);
            instance.appendChild(instanceIdElement);

            Element hostNameElement = document.createElement("hostName");
            hostNameElement.setTextContent(hostName);
            instance.appendChild(hostNameElement);

            Element appElement = document.createElement("app");
            appElement.setTextContent(app);
            instance.appendChild(appElement);

            Element ipAddrElement = document.createElement("ipAddr");
            ipAddrElement.setTextContent(ipAddr);
            instance.appendChild(ipAddrElement);

            Element statusElement = document.createElement("status");
            statusElement.setTextContent(status);
            instance.appendChild(statusElement);

            Element portElement = document.createElement("port");
            portElement.setAttribute("enabled", "true");
            portElement.setTextContent(port);
            instance.appendChild(portElement);

            Element securePortElement = document.createElement("securePort");
            securePortElement.setTextContent("443");
            securePortElement.setAttribute("enabled", "false");
            instance.appendChild(securePortElement);

            Element dataCenterInfoElement = document.createElement("dataCenterInfo");
            dataCenterInfoElement.setAttribute("class", "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo");
            Element dataCenterInfoNameElement = document.createElement("name");
            dataCenterInfoNameElement.setTextContent("MyOwn");
            dataCenterInfoElement.appendChild(dataCenterInfoNameElement);
            instance.appendChild(dataCenterInfoElement);

            //自定义参数
            Element metadataElement = document.createElement("metadata");
            metadataElement.setAttribute("class", "java.util.Collections$EmptyMap");
            Element metadataActorElement = document.createElement("depend-server");
            metadataActorElement.setTextContent("AOIS-Tactics-Service,AOIS-Fix-Service");
            metadataElement.appendChild(metadataActorElement);

            instance.appendChild(metadataElement);

            Element homePageUrlElement = document.createElement("homePageUrl");
            homePageUrlElement.setTextContent(homePageUrl);
            instance.appendChild(homePageUrlElement);

            Element statusPageUrlElement = document.createElement("statusPageUrl");
            statusPageUrlElement.setTextContent(statusPageUrl);
            instance.appendChild(statusPageUrlElement);

            Element healthCheckUrlElement = document.createElement("healthCheckUrl");
            healthCheckUrlElement.setTextContent(healthCheckUrl);
            instance.appendChild(healthCheckUrlElement);

            Element vipAddressElement = document.createElement("vipAddress");
            vipAddressElement.setTextContent(vipAddress);
            instance.appendChild(vipAddressElement);

            Element secureVipAddressElement = document.createElement("secureVipAddress");
            secureVipAddressElement.setTextContent(secureVipAddress);
            instance.appendChild(secureVipAddressElement);

            document.appendChild(instance);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");//使用换行

            StringWriter stringWriter = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(stringWriter));

            System.out.println(stringWriter.toString());
            return stringWriter.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void registEurekaApp() {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL("http://127.0.0.1:15000/eureka/apps/standalone");
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/xml");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            String xmlinfo = InstanceUtil.createXml();
            out.write(xmlinfo);
            out.flush();
            out.close();

            System.out.println(conn.getResponseCode());

            if (conn.getResponseCode() == 204) {
                System.out.println("微服务注册成功!");
                InstanceUtil.REGIST_STATUS = 0;
                InstanceUtil.FAIL_TIME = 0;

            } else {
                System.out.println("微服务注册失败!");
                InstanceUtil.REGIST_STATUS = -1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
    }


    public static void refreshHeartBeat(String urlHeartBeat) {
        if (3 == InstanceUtil.FAIL_TIME) {
            System.out.println("心跳连续失败三次,不再传递");
            return;
        }
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL("http://127.0.0.1:15000/eureka/apps/standalone/standalone:20000");
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();

                System.out.println("心跳传递成功!");
                InstanceUtil.FAIL_TIME = 0;

            } else {
                System.out.println("心跳传递失败!");

                InstanceUtil.FAIL_TIME = InstanceUtil.FAIL_TIME + 1;
                if (3 == InstanceUtil.FAIL_TIME) {
                    InstanceUtil.REGIST_STATUS = -1;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
    }


    public static void deleteEurekaApp() {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL("http://127.0.0.1:15000/eureka/apps/standalone/standalone:20000");
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("DELETE");

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            if (conn.getResponseCode() == 200) {
                System.out.println("微服务注销成功!");
            } else {
                System.out.println("微服务注销失败!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
    }


    public static String queryEurekaApp() {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL("http://127.0.0.1:15000/eureka/apps");
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/xml");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            System.out.println(conn.getResponseCode());

            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                System.out.println("查询注册中心成功:" + "\n" + baos.toString());
                return baos.toString();

            } else {
                System.out.println("查询失败~！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            conn.disconnect();
        }
        return null;
    }







}
